package org.ezplatform.component.wps.document.web.rest;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.ezplatform.component.attachment.entity.Attachment;
import org.ezplatform.component.attachment.service.AttachmentService;
import org.ezplatform.component.attachment.util.AttachUtils;
import org.ezplatform.component.common.service.NetdistFileDealApiService;
import org.ezplatform.component.goldgrid.common.dto.GoldgridDto;
import org.ezplatform.component.goldgrid.common.service.GoldgridSubjectService;
import org.ezplatform.component.goldgrid.document.entity.DocumentFile;
import org.ezplatform.component.goldgrid.document.service.DocumentFileService;
import org.ezplatform.component.goldgrid.template.service.TemplateFileService;
import org.ezplatform.component.goldgrid.util.GoldgridSecUtils;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.system.auth.util.AuthUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.MD5Utils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * documentfile页面控制类
 *
 */
@Api(value = "wps文件api", tags = "wps文件API")
@RestController
@RequestMapping(value = "/api/w/cmp/wps/documentfile")
public class WpsDocumentFileWebApiController extends BaseController<DocumentFile, String> {

	private static final Logger LOGGER = LoggerFactory.getLogger(WpsDocumentFileWebApiController.class);

	private String msg = "";// 返回信息
	private Map<String, GoldgridDto> goldgridDtoMap = new HashMap<String, GoldgridDto>();

	@Autowired
	private DocumentFileService service;
	
	@Autowired
	private TemplateFileService templateFileService;

	@Autowired
	private GoldgridSubjectService goldgridSubjectService;
	
	@Autowired
    private AttachmentService attachmentService;
	
	@Autowired
	private NetdistFileDealApiService netdistFileDealApiService;

	/*
	 * (非 JAVADOC) <p>Title: getEntityService</p> <p>Description: </p>
	 * 
	 * @return
	 * 
	 */
	@Override
	protected BaseService<DocumentFile, String> getEntityService() {
		return service;
	}

	/**
	 * 
	 * @Title: prepareModel @Description: 初始化数据 @param request @param model @param
	 *         id @return void @throws
	 */
	@ModelAttribute
	public void prepareModel(HttpServletRequest request, Model model,
			@RequestParam(value = "id", required = false) String id) {
		super.initPrepareModel(request, model, id);
	}

	/**
	 * 金格传参map
	 */
	@ApiOperation(value = "设置金格传参", notes = "设置金格传参")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "recordId", value = "文档id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "id", value = "记录id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "isNetdisk", value = "是否是网盘1是0否", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "isAttachment", value = "是否是附件1是0否", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "editType", value = "编辑类型：edit在线编辑view预览", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "showType", value = "显示类型",  paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "showEditbutton", value = "显示编辑按钮",  paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "isTemplate", value = "是否是模板1是0否",  paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "templateId", value = "模板id",  paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "loadTemp", value = "是否加载模板1是0否",  paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "fileName", value = "文件名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "displayFilename", value = "文件显示名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "fileType", value = "文件类型", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "moduleCode", value = "模块编码", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userName", value = "用户名", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "corpId", value = "单位id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "isSingnatruePdf", value = "是否显示转换pdf",  paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "isShowTempsign", value = "是否显示选择模板、签名签章",  paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "isPrintFileButn", value = "是否显示打印文档", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "unlockUrl", value = "工作网盘解锁url回调地址", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "templateBookmarks", value = "模板书签值", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "wpsonlineEditUrl", value = "wps在线编辑url", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "secdatacode", value = "越权校验码", required = true, paramType = "query", dataType = "String")
	})
	@RequestMapping(value = "/setGoldgridDtoMap", method = RequestMethod.POST)
	@ResponseBody
	public OperationResult setGoldgridDtoMap(HttpServletRequest request) {
		try {
			WebUser user = AuthUtils.getCurrentUser();
			String recordId = request.getParameter("recordID");
			String secdatacode = request.getParameter("secdatacode");
			if(!GoldgridSecUtils.checkDataByRecordIdUserIdExt(secdatacode,user.getUserId(),recordId)) {
				return OperationResult.buildFailureResult("参数非法");
			}
			goldgridSubjectService.setGoldgridDtoMap(request);
			String flexServerFullPath = GlobalConstant.getFlexServerFullPath(request);
			Map<String,String> resultMap = new HashMap<String,String>();
			resultMap.put("flexServerFullPath", flexServerFullPath);
			return OperationResult.buildSuccessResult(resultMap);
		}catch(Exception e) {
			LOGGER.error(e.getMessage(),e);
			return OperationResult.buildFailureResult("操作失败");
		}
	}
	
	/**
	 * 获取进入新增/修改页面数据
	 * 
	 * @param model
	 * @return page
	 */
	@ApiOperation(value = "获取金格参数", notes = "获取金格参数")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "金格缓存数据id", required = true, paramType = "query", dataType = "String"),
	})
	@RequestMapping(value = "/documentEdit", method = RequestMethod.GET)
	public OperationResult documentEdit(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		OperationResult  goldgridDtoResult= this.goldgridSubjectService.getGoldgridDtoAttr(request,request.getParameter("id"));
		map = (Map<String,Object>)goldgridDtoResult.getData();
		
		WebUser user = WebUtils.getCurrentUser(); 
		// 文档id
		String recordId = map.get("recordID")==null?"":map.get("recordID").toString();
		String corpId = map.get("corpId")==null?"":map.get("corpId").toString();
		//模板信息 
		String templateId = map.get("templateId")==null?"":map.get("templateId").toString();
		String loadTemp = map.get("loadTemp")==null?"":map.get("loadTemp").toString();
		//是否可编辑
		String editType= map.get("editType")==null?"":map.get("editType").toString();

		String fileId = map.get("fileId")==null?"":map.get("fileId").toString();
		String fileSuffix= map.get("fileType")==null?"":map.get("fileType").toString();
		String fileName= map.get("fileName")==null?"":map.get("fileName").toString();
		String isAttachment= map.get("isAttachment")==null?"0":map.get("isAttachment").toString();
		String isNetdisk= map.get("isNetdisk")==null?"sys":map.get("isNetdisk").toString();
		String moduleCode= map.get("moduleCode")==null?"goldgrid":map.get("moduleCode").toString();

		Attachment attachment = this.service.getAttachmentFile(recordId, corpId);
		// 判断是否要加载模版
		if ("1".equals(editType)&&loadTemp != null && "1".equals(loadTemp) &&StringUtils.isNotEmpty(templateId)) {
			Attachment templateattachment = this.templateFileService.getAttachmentFile(templateId, corpId);
			if (templateattachment == null) {
				templateattachment = new Attachment();
			}
			map.put("templateFileId", templateattachment.getId());
			map.put("templatechecksum", templateattachment.getChecksum()); 
		}
		Map<String,String> fileInfo = this.service.getFileInfoMap(request,attachment,recordId,fileId,corpId,editType,fileSuffix,fileName,isAttachment,isNetdisk,moduleCode,user.getUserId(),user.getJwtToken());
		map.put("fileId", fileInfo.get("fileId"));
		map.put("checksum", fileInfo.get("checksum"));
		if("1".equals(isAttachment)){
			map.put("fileName", fileInfo.get("fileName"));
		}
		return OperationResult.buildSuccessResult(map);
	}
	
	/**
	 * 获取附件在线编辑进入新增/修改页面数据
	 * 
	 * @param model
	 * @return page
	 */
	@ApiOperation(value = "获取附件在线编辑进入新增/修改页面数据", notes = "获取附件在线编辑进入新增/修改页面数据")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "金格缓存数据id", required = true, paramType = "query", dataType = "String"),
	})
	@RequestMapping(value = "/attchmentDocumentEdit", method = RequestMethod.GET)
	public OperationResult attchmentDocumentEdit(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		OperationResult  goldgridDtoResult= this.goldgridSubjectService.getGoldgridDtoAttr(request,request.getParameter("id"));
		map = (Map<String,Object>)goldgridDtoResult.getData();
		
		WebUser user = WebUtils.getCurrentUser();
		//附件fileId 
		String fileId = map.get("fileId")==null?"":map.get("fileId").toString();
		Attachment attachment = this.attachmentService.findOne(fileId);
		if (attachment == null) {
			attachment = new Attachment();
		}
		map.put("fileId", attachment.getId());
		map.put("checksum", attachment.getChecksum());

		
		return OperationResult.buildSuccessResult(map);
	}
	
	/**
	 * 获取网盘附件在线编辑进入新增/修改页面数据
	 * 
	 * @return page
	 */
	@ApiOperation(value = "获取网盘附件在线编辑进入新增/修改页面数据", notes = "获取网盘附件在线编辑进入新增/修改页面数据")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "金格缓存数据id", required = true, paramType = "query", dataType = "String"),
	})
	@RequestMapping(value = "/attchmentDocumentEditNetdisk", method = RequestMethod.GET)
	public OperationResult attchmentDocumentEditNetdisk(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		Map<String,Object> map = new HashMap<String,Object>();
		OperationResult  goldgridDtoResult= this.goldgridSubjectService.getGoldgridDtoAttr(request,request.getParameter("id"));
		map = (Map<String,Object>)goldgridDtoResult.getData();
		//附件fileId
		String fileId = map.get("fileId")==null?"":map.get("fileId").toString();
		
		Map<String,Object> tempMap = netdistFileDealApiService.getFileInfoMap(fileId,user.getUserId(),user.getJwtToken());
		map.put("checksum", tempMap.get("checksum"));
		return OperationResult.buildSuccessResult(map);
	}

	/**
	 * 套红时--html文本标签替换
	 *
	 * @return page
	 */
	@RequestMapping(value = "/delDocumentHtmlTag", method = RequestMethod.POST)
	@ResponseBody
	public OperationResult delDocumentHtmlTag(HttpServletRequest request) {
		String path = "";
		String content = request.getParameter("content");
		String moduleCode = request.getParameter("moduleCode");
		StringBuffer sb = new StringBuffer("<html>");
		String fileName = UuidUtils.UUID() +".html";
		sb.append("<body>");
		sb.append(content);
		sb.append("</body>");
		sb.append("</html>");

		AttachUtils attachUtils = new AttachUtils();
		String absolutePath = "";
		absolutePath = attachUtils.getUploadAbsolutePath(request,AttachUtils.TEMP_FILEUPLOADPATH_TYPE_EMPTY);
		path = absolutePath + "/" + moduleCode + "/" + fileName;
		File file = new File(path);
		if (!file.getParentFile().exists()) { // 如果文件的目录不存在
			file.getParentFile().mkdirs(); // 创建目录
		}
		FileWriter writer = null;
		try{
			writer = new FileWriter(path);
			writer.write("");//清空源文件
			writer.write(sb.toString());
			writer.flush();
		}catch (Exception e){
			LOGGER.error(e.getMessage(),e);
		}finally {
			if(writer!=null){
				try {
					writer.close();
				} catch (IOException e) {
					LOGGER.error(e.getMessage(),e);
				}
			}
		}

		Attachment attachment = new Attachment();
		attachment.setFileName(fileName);
		attachment.setFileDisplayName(fileName);
		attachment.setFileExt(".html");
		attachment.setFileSize(attachment.getFileSize());
		attachment.setRelativePath(moduleCode);
		attachment.setClientIp(org.ezplatform.util.IPAddrFetcher.getRemoteIpAddress(request));
		attachment.setFileSource(Attachment.FileSource.PC);
		attachment.setDelFlag("0");
		String checksum = MD5Utils.hash(fileName);
		attachment.setChecksum(checksum);
		attachment.setCleanFlag(0);
		attachment.setPreviewDate(null);
		attachmentService.save(attachment);

		String fid = attachment.getId();
		Map<String,String> map = new HashMap<String,String>();
		map.put("fid",fid);
		map.put("checksum",checksum);
		return OperationResult.buildSuccessResult("操作成功",map);
	}
}
